{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Example: Static forward free-boundary equilibrium calculations (in MAST)\n", "\n", "---\n", "\n", "Here we will show how to solve for equilibria on MAST, the predecessor of MAST-U.\n", "\n", "The machine geometry (active coils, passive structures, limiter, and wall) comes from the public [FAIR-MAST](https://ukaea.github.io/fair-mast/) database (which also contains lots of other open-source shot data from MAST!). \n", "\n", "In this notebook, the coil currents, passive structure currents, and profiles come from FAIR-MAST but are stored locally for easy access. They are based on the EFIT reconstruction of MAST shot 30421 at 0.25 s.\n", "\n", "The local data is stored in `data/MAST_30421_0.25s.json`, together with the EFIT data for comparison.\n", "\n", "Other recent work using FreeGSNKE on MAST equilibria can be found here:\n", "- [Fair-MAST-to-FreeGSNKE-Conversion-tool](https://github.com/afshin-arj/Fair-MAST-to-FreeGSNKE-Conversion-tool)\n", "- [mast-bridge](https://github.com/Homingdung/mast-bridge)" ] }, { "cell_type": "markdown", "id": "1", "metadata": {}, "source": [ "### Import packages" ] }, { "cell_type": "code", "execution_count": null, "id": "2", "metadata": {}, "outputs": [], "source": [ "import json\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np" ] }, { "cell_type": "markdown", "id": "3", "metadata": {}, "source": [ "### Create the machine object" ] }, { "cell_type": "code", "execution_count": null, "id": "4", "metadata": {}, "outputs": [], "source": [ "# build machine\n", "from freegsnke import build_machine\n", "\n", "tokamak = build_machine.tokamak(\n", " active_coils_path=\"../machine_configs/MAST/MAST_active_coils.pickle\",\n", " passive_coils_path=\"../machine_configs/MAST/MAST_passive_coils.pickle\",\n", " limiter_path=\"../machine_configs/MAST/MAST_limiter.pickle\",\n", " wall_path=\"../machine_configs/MAST/MAST_wall.pickle\",\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "5", "metadata": {}, "outputs": [], "source": [ "# plot the machine\n", "fig, ax = plt.subplots(figsize=(6, 10), dpi=80)\n", "\n", "tokamak.plot(axis=ax, show=False) # plots the active coils and passive structures\n", "ax.plot(tokamak.limiter.R, tokamak.limiter.Z, \"k-\", linewidth=1.2) # plots the limiter\n", "ax.grid(alpha=0.5)\n", "ax.set_aspect(\"equal\")\n", "ax.set_xlim(0.0, 2.15)\n", "ax.set_ylim(-2.6, 2.6)\n", "ax.set_xlabel(r\"Major radius, $R$ [m]\")\n", "ax.set_ylabel(r\"Height, $Z$ [m]\")" ] }, { "cell_type": "markdown", "id": "6", "metadata": {}, "source": [ "### Instantiate an equilibrium" ] }, { "cell_type": "code", "execution_count": null, "id": "7", "metadata": {}, "outputs": [], "source": [ "from freegsnke import equilibrium_update\n", "\n", "eq = equilibrium_update.Equilibrium(\n", " tokamak=tokamak, # provide tokamak object\n", " Rmin=0.06, Rmax=1.98, # radial range (same as the EFIT grid)\n", " Zmin=-2.0, Zmax=2.0, # vertical range (same as the EFIT grid)\n", " nx=129, # number of radial grid points (needs to be of the form 2**n + 1)\n", " ny=129, # number of vertical grid points (needs to be of the form 2**n + 1)\n", ")" ] }, { "cell_type": "markdown", "id": "8", "metadata": {}, "source": [ "### Load the EFIT data and instantiate a profile object" ] }, { "cell_type": "code", "execution_count": null, "id": "9", "metadata": {}, "outputs": [], "source": [ "# EFIT reconstruction of MAST shot 30421 at 0.25 s\n", "with open(\"data/MAST_30421_0.25s.json\") as f:\n", " efit = json.load(f)\n", "\n", "from freegsnke.jtor_update import GeneralPprimeFFprime\n", "\n", "profiles = GeneralPprimeFFprime(\n", " eq=eq, # equilibrium object\n", " Ip=efit[\"Ip\"], # plasma current [A]\n", " fvac=efit[\"fvac\"], # fvac = R * B_tor [T m]\n", " psi_n=np.array(efit[\"psi_n\"]), # normalised poloidal flux\n", " pprime_data=np.array(efit[\"pprime\"]), # pressure derivative profile\n", " ffprime_data=np.array(efit[\"ffprime\"]), # FF' profile\n", " p_data=np.array(efit[\"pressure\"]), # pressure profile (optional)\n", " f_data=np.array(efit[\"f\"]), # F profile (optional)\n", " Ip_logic=True,\n", ")" ] }, { "cell_type": "markdown", "id": "10", "metadata": {}, "source": [ "### Set the coil currents\n", "\n", "EFIT gives one current for each circuit. We convert these currents to FreeGSNKE coil currents as follows:\n", "- The shaping coil currents (P2 to P6) are in ampere-turns, so we divide them by the number of turns in each coil.\n", "- The solenoid (SOL) current is multiplied by 0.5 because of its wiring.\n", "- Each PF coil case is one EFIT circuit, but it is made of a number of separate elements in FreeGSNKE. We split the case current across these elements in proportion to their areas.\n", "- All other passive structure currents are used as they are." ] }, { "cell_type": "code", "execution_count": null, "id": "11", "metadata": {}, "outputs": [], "source": [ "currents = efit[\"currents\"]\n", "\n", "# active coils\n", "for name in efit[\"actives_order\"]:\n", " if name == \"SOL\":\n", " value = 0.5 * currents[name]\n", " else:\n", " value = currents[name] / len(tokamak.coils_dict[name][\"coords\"][0])\n", " tokamak.set_coil_current(coil_label=name, current_value=value)\n", "\n", "# passive structures\n", "for name in efit[\"passives_order\"]:\n", " if name.startswith(\"coil_cases\"):\n", " case = \"coil_cases_\" + name[-3:] # e.g. \"coil_cases_P2U\"\n", " elements = [c for c in tokamak.coil_names if case in c]\n", " areas = np.array([tokamak.coils_dict[e][\"area\"] for e in elements])\n", " for element, area in zip(elements, areas):\n", " tokamak.set_coil_current(coil_label=element, current_value=currents[name] * area / areas.sum())\n", " else:\n", " tokamak.set_coil_current(coil_label=name, current_value=currents[name])" ] }, { "cell_type": "markdown", "id": "12", "metadata": {}, "source": [ "### The forward solve" ] }, { "cell_type": "code", "execution_count": null, "id": "13", "metadata": {}, "outputs": [], "source": [ "# load the static nonlinear solver\n", "from freegsnke import GSstaticsolver\n", "from freegsnke.equilibrium import PsiGuessParabolicJtor\n", "\n", "GSStaticSolver = GSstaticsolver.NKGSsolver(eq, seed=42)\n", "\n", "# put the initial guess near the EFIT magnetic axis (below the midplane),\n", "# so that the solver finds the lower X-point configuration\n", "psi_guess = PsiGuessParabolicJtor(\n", " h=efit[\"axis\"][0], # radial centre of ellipse\n", " k=efit[\"axis\"][1], # vertical centre of ellipse\n", " a=0.5, # approximate radial minor radius of the plasma\n", " b=0.9, # approximate vertical minor radius of the plasma\n", " Ip=profiles.Ip, # plasma current used to scale the guess\n", " psi_scale=1.0, # scaling factor for the initial flux guess\n", ")\n", "eq.plasma_psi = psi_guess(eq=eq)\n", "\n", "# carry out the forward solve with fixed coil currents\n", "GSStaticSolver.forward_solve(\n", " eq=eq,\n", " profiles=profiles,\n", " target_relative_tolerance=1e-7,\n", " max_solving_iterations=100,\n", " verbose=True, # print output\n", ")" ] }, { "cell_type": "markdown", "id": "14", "metadata": {}, "source": [ "### Plot the equilibrium and compare with EFIT" ] }, { "cell_type": "code", "execution_count": null, "id": "15", "metadata": {}, "outputs": [], "source": [ "efit_lcfs = np.array(efit[\"lcfs\"])\n", "efit_xpoints = np.array(efit[\"xpoints\"])\n", "\n", "fig, ax = plt.subplots(figsize=(6, 10), dpi=80)\n", "\n", "ax.grid(zorder=0, alpha=0.75)\n", "ax.set_aspect(\"equal\")\n", "eq.tokamak.plot(axis=ax, show=False) # plots the active coils and passive structures\n", "eq.plot(axis=ax, show=False) # plots the equilibrium\n", "ax.plot(tokamak.limiter.R, tokamak.limiter.Z, \"k-\", linewidth=1.2) # plots the limiter\n", "ax.plot(efit_lcfs[:, 0], efit_lcfs[:, 1], \"m--\", linewidth=1.5, label=\"EFIT LCFS\")\n", "ax.plot(efit_xpoints[:, 0], efit_xpoints[:, 1], \"mx\", markersize=10, label=\"EFIT X-points\")\n", "ax.legend(loc=\"upper right\")\n", "ax.set_xlim(0.0, 2.15)\n", "ax.set_ylim(-2.6, 2.6)\n", "ax.set_xlabel(r\"Major radius, $R$ [m]\")\n", "ax.set_ylabel(r\"Height, $Z$ [m]\")" ] }, { "cell_type": "code", "execution_count": null, "id": "16", "metadata": {}, "outputs": [], "source": [ "from scipy.spatial.distance import cdist\n", "\n", "# --- Extract FreeGSNKE and EFIT quantities ---\n", "fg_sep = eq.separatrix(ntheta=360)\n", "efit_axis = np.array(efit[\"axis\"])\n", "\n", "# Match EFIT X-points to the nearest FreeGSNKE X-points\n", "fg_xpt_low = eq.xpt[np.argmin(np.linalg.norm(eq.xpt[:, :2] - efit_xpoints[0], axis=1)), :2]\n", "fg_xpt_up = eq.xpt[np.argmin(np.linalg.norm(eq.xpt[:, :2] - efit_xpoints[1], axis=1)), :2]\n", "\n", "# Geometric & shaping parameters from EFIT LCFS\n", "Rmin_e, Rmax_e = efit_lcfs[:, 0].min(), efit_lcfs[:, 0].max()\n", "Zmin_e, Zmax_e = efit_lcfs[:, 1].min(), efit_lcfs[:, 1].max()\n", "Rgeo_e = 0.5 * (Rmax_e + Rmin_e)\n", "Zgeo_e = 0.5 * (Zmax_e + Zmin_e)\n", "a_e = 0.5 * (Rmax_e - Rmin_e)\n", "A_e = Rgeo_e / a_e\n", "kappa_e = (Zmax_e - Zmin_e) / (Rmax_e - Rmin_e)\n", "delta_u_e = (Rgeo_e - efit_lcfs[np.argmax(efit_lcfs[:, 1]), 0]) / a_e\n", "delta_l_e = (Rgeo_e - efit_lcfs[np.argmin(efit_lcfs[:, 1]), 0]) / a_e\n", "\n", "# Cross-sectional area of EFIT LCFS (shoelace formula)\n", "efit_area = 0.5 * np.abs(\n", " np.dot(efit_lcfs[:, 0], np.roll(efit_lcfs[:, 1], -1))\n", " - np.dot(efit_lcfs[:, 1], np.roll(efit_lcfs[:, 0], -1))\n", ")\n", "\n", "# Nearest-point distances between FreeGSNKE separatrix and EFIT LCFS\n", "dist_matrix = cdist(fg_sep, efit_lcfs)\n", "d_fg_to_efit = dist_matrix.min(axis=1)\n", "d_efit_to_fg = dist_matrix.min(axis=0)\n", "hausdorff_dist = max(d_fg_to_efit.max(), d_efit_to_fg.max())\n", "\n", "# --- Print summary comparison table ---\n", "print(\"=\" * 74)\n", "print(f\"FreeGSNKE vs EFIT Comparison (MAST shot {efit['shot']}, t = {efit['time']:.2f} s)\")\n", "print(\"=\" * 74)\n", "print(f\"{'Quantity':<28} {'FreeGSNKE':>14} {'EFIT':>14} {'Diff':>14}\")\n", "print(\"-\" * 74)\n", "print(f\"{'Plasma current Ip [kA]':<28} {eq.plasmaCurrent()*1e-3:>14.2f} {efit['Ip']*1e-3:>14.2f} {(eq.plasmaCurrent() - efit['Ip'])*1e-3:>+14.2f}\")\n", "print(f\"{'R_axis [m]':<28} {eq.opt[0, 0]:>14.4f} {efit_axis[0]:>14.4f} {eq.opt[0, 0] - efit_axis[0]:>+14.4f}\")\n", "print(f\"{'Z_axis [m]':<28} {eq.opt[0, 1]:>14.4f} {efit_axis[1]:>14.4f} {eq.opt[0, 1] - efit_axis[1]:>+14.4f}\")\n", "print(f\"{'R_X,low [m]':<28} {fg_xpt_low[0]:>14.4f} {efit_xpoints[0, 0]:>14.4f} {fg_xpt_low[0] - efit_xpoints[0, 0]:>+14.4f}\")\n", "print(f\"{'Z_X,low [m]':<28} {fg_xpt_low[1]:>14.4f} {efit_xpoints[0, 1]:>14.4f} {fg_xpt_low[1] - efit_xpoints[0, 1]:>+14.4f}\")\n", "print(f\"{'R_X,up [m]':<28} {fg_xpt_up[0]:>14.4f} {efit_xpoints[1, 0]:>14.4f} {fg_xpt_up[0] - efit_xpoints[1, 0]:>+14.4f}\")\n", "print(f\"{'Z_X,up [m]':<28} {fg_xpt_up[1]:>14.4f} {efit_xpoints[1, 1]:>14.4f} {fg_xpt_up[1] - efit_xpoints[1, 1]:>+14.4f}\")\n", "print(f\"{'R_geo [m]':<28} {eq.Rgeometric():>14.4f} {Rgeo_e:>14.4f} {eq.Rgeometric() - Rgeo_e:>+14.4f}\")\n", "print(f\"{'Z_geo [m]':<28} {eq.Zgeometric():>14.4f} {Zgeo_e:>14.4f} {eq.Zgeometric() - Zgeo_e:>+14.4f}\")\n", "print(f\"{'Minor radius a [m]':<28} {eq.minorRadius():>14.4f} {a_e:>14.4f} {eq.minorRadius() - a_e:>+14.4f}\")\n", "print(f\"{'Aspect ratio A':<28} {eq.aspectRatio():>14.4f} {A_e:>14.4f} {eq.aspectRatio() - A_e:>+14.4f}\")\n", "print(f\"{'Elongation kappa':<28} {eq.geometricElongation():>14.4f} {kappa_e:>14.4f} {eq.geometricElongation() - kappa_e:>+14.4f}\")\n", "print(f\"{'Upper triangularity delta_u':<28} {eq.triangularity_upper():>14.4f} {delta_u_e:>14.4f} {eq.triangularity_upper() - delta_u_e:>+14.4f}\")\n", "print(f\"{'Lower triangularity delta_l':<28} {eq.triangularity_lower():>14.4f} {delta_l_e:>14.4f} {eq.triangularity_lower() - delta_l_e:>+14.4f}\")\n", "print(f\"{'Separatrix area [m^2]':<28} {eq.separatrix_area():>14.4f} {efit_area:>14.4f} {eq.separatrix_area() - efit_area:>+14.4f}\")\n", "print(\"-\" * 74)\n", "print(f\"Magnetic axis separation : {np.linalg.norm(eq.opt[0, :2] - efit_axis)*1e3:.2f} mm\")\n", "print(f\"Lower X-point separation : {np.linalg.norm(fg_xpt_low - efit_xpoints[0])*1e3:.2f} mm\")\n", "print(f\"Upper X-point separation : {np.linalg.norm(fg_xpt_up - efit_xpoints[1])*1e3:.2f} mm\")\n", "print(f\"LCFS distance (FG -> EFIT) : mean = {d_fg_to_efit.mean()*1e3:.2f} mm, RMS = {np.sqrt(np.mean(d_fg_to_efit**2))*1e3:.2f} mm, max = {d_fg_to_efit.max()*1e3:.2f} mm\")\n", "print(f\"LCFS Hausdorff distance : {hausdorff_dist*1e3:.2f} mm\")\n", "print(f\"FreeGSNKE derived metrics : beta_p = {eq.poloidalBeta():.3f}, li(1) = {eq.internalInductance1():.3f}, V_p = {eq.plasmaVolume():.3f} m^3\")\n", "print(\"=\" * 74)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "17", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "18", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "freegsnke", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.20" } }, "nbformat": 4, "nbformat_minor": 5 }